#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Created on 2013-9-4

@author: iori
'''
import re, os
import urllib
import unittest
from pyquery import PyQuery
from datetime import datetime
def et8(key='', days=2, path='.'):
    ''' 用来下载ET8'''
    row = 10
    key = 'BMDruCHinYaN' if not key else key
    passkey = '61a34a6282dbd13318e4bede131ea1f5'
    url = 'http://et8.org/torrentrss.php?rows=%d&search=%s&search_mode=1&\
            linktype=dl&passkey=%s'%(row, key, passkey)
    fn = 'torrentrss.xml'
    pq = PyQuery(url)
    for i in xrange(len(pq('item'))):
        item = pq('item').eq(i)
        item = PyQuery(item.html())
        bt_url = item('enclosure').attr.url
        pub_date = item('pubDate').text()  # Tue, 03 Sep 2013 21:26:07 +0800
        pub_date = datetime.strptime(pub_date[:-7], '%a, %d %b %Y %H:%M:%S')
        if days < (datetime.now()- pub_date).days: continue
        tid = re.findall(r'id=(\d+)', bt_url)[0]
        fpath = os.path.join(path, '%s.torrent'%tid)
        cpath = os.path.join(path, 'torrent.cfg')
        conf = []
        if os.path.isfile(cpath):
            with open(cpath, 'rb') as fp:
                conf = fp.read().split('\n')
        if conf and tid in conf: continue
        conf.append(tid)
        res = urllib.urlopen(bt_url)
        with open(fpath, 'wb') as fp:
            fp.write(res.read())
        with open(cpath, 'wb') as fp:
            fp.write('\n'.join(conf))
            
class TestTorrent(unittest.TestCase):
    def test_et8(self):
        et8()
    
if __name__ == '__main__':
    unittest.main()